import React from 'react';
import { connect } from 'react-redux';
import moment from 'moment'
import {
  Form,
  Row,
  Tabs,
  Button,
  Checkbox,
  Table,
  Divider,
  Modal,
  Badge,
  Spin
} from 'antd'
import 'styles/setting/workflow/new-workflow.scss'
import FullScreen from 'components/full-screen'
const TabPane = Tabs.TabPane;
import 'styles/pay-setting/payment-method/new-payment-method.scss'
import { messages } from 'share/common'
import errorMessage from 'share/errorMessage'

import FormSetting from 'containers/setting/workflow/right-content/form-setting'
import NewWorkflowDetail from 'containers/setting/new-workflow/detail/workflow-detail'
import CopySelectForm from 'containers/setting/new-workflow/list-comp/copy-comp/select-form'
import 'styles/setting/workflow/workflow-detail.scss'
import 'styles/setting/workflow/new-workflow.scss'
import workflowService from 'containers/setting/workflow/workflow.service'
import newWorkflowService from 'containers/setting/new-workflow/new-workflow.service'
import ResizeTable from "components/resize-table";
//redux
import { setWorkflowDepartmentPosition } from "actions/cache";

class NewWorkingRightContent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      nowNode: {},
      approveRuleModalVisible: false,
      columns: [{
        title: messages('setting.key1971')/*版本号*/,
        dataIndex: 'version',
        key: 'version',
        width: 120,
        sorter: (a, b) => {
          let aArr = a.version.split('.');
          let bArr = b.version.split('.');
          if (aArr[0] === bArr[0]) {
            return bArr[1] - aArr[1]
          } else if (aArr[0] > bArr[0]) {
            return -1
          } else if (aArr[0] < bArr[0]) {
            return 1
          }
        },
      }, {
        title: messages('setting.key1969')/*审批流名称*/,
        dataIndex: 'name',
        key: 'name',
        // sorter: (a, b) => a.name.localeCompare(b.name, 'zh-Hans-CN', { sensitivity: 'accent' }),
      }, {
        title: messages('setting.key1096')/*状态*/,
        dataIndex: 'used',
        key: 'used',
        width: 100,
        sorter: (a, b) => b.used - a.used,
        render: valid =>
          <Badge status={valid ? 'success' : 'default'}
                 text={valid ? messages('setting.key1086')/*启用*/ : messages('setting.key1916')/*停用*/}/>,
      }, {
        title: messages('setting.key1970')/*最后修改时间*/,
        key: 'lastModifiedDate',
        width: 180,
        dataIndex: 'lastModifiedDate',
        render: value => moment(value).format('YYYY-MM-DD HH:mm'),
        sorter: (a, b) => new Date(b.lastModifiedDate).getTime() - new Date(a.lastModifiedDate).getTime(),
      }, {
        title: messages('setting.key1147')/*操作*/,
        key: 'action',
        render: (text, record) => this.action(record),
      }],
      data: [],
      checkDisable: true,
      copyData: [],
      loading: false,
      formOID: null,
      defaultActiveKey: '1',
      visible: false,
      mode: 'create',
      nodeList: [],
    };
  }

  action = (record) => {
    const { setOfBooksId } = this.props;
    let { formOID } = this.state;
    return (
      <span>
        <a>
          <span onClick={() => this.goDetail(record)}>{messages('setting.key1071')/*编辑*/}</span>
        </a>
        <Divider type="vertical"/>
        <a onClick={() => this.handleChangeStatus(record)}>{!record.used ? messages('setting.key1086')/*启用*/ : messages('setting.key1087')/*禁用*/}</a>
        <Divider type="vertical"/>
        <a>
          <CopySelectForm text={messages('setting.key1430')/*复制*/}
                          copySuccess={this.handleCopySuccess}
                          formOID={formOID}
                          version={record.version}
                          setOfBooksId={setOfBooksId}/>
        </a>
        <Divider type="vertical"/>
        <a onClick={() => this.handleDeleteWorkflow(record)}>{messages('setting.key1101')/*删除*/}</a>
      </span>)
  };

  //进入详情页
  goDetail = (record) => {
    if (Number(record.version.split('.')[0].replace('V', "")) > 0) {
      this.setState({ visible: true, mode: 'edit', version: record.version })
    } else {
      this.props.onSelectOldDetail(record);
    }
  };

  componentWillMount() {
    this.setState({
      formOID: this.props.formOID,
      formType :this.props.formType,
      defaultActiveKey: '1',
    });
    this.setState({ loading: true, })
    Promise.all([
      this.getVersionList(this.props.formOID),
      this.getNodeList(this.props.formOID)]),
      this.getDepartmentPositionList()
      .then(() => {
        this.setState({ loading: false });
      })
      .catch(() => {
        this.setState({ loading: false });
      });
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.formOID !== this.state.formOID) {
      this.setState({
        formOID: nextProps.formOID,
        formType :nextProps.formType,
        defaultActiveKey: '1',
      });
      this.setState({ loading: true, });
      Promise.all([
        this.getVersionList(nextProps.formOID),
        this.getNodeList(nextProps.formOID)]),
        this.getDepartmentPositionList()
        .then(() => {
          this.setState({ loading: false });
        })
        .catch(() => {
          this.setState({ loading: false });
        });
    }
  }

  getDepartmentPositionList = () => {
    return workflowService.getDepartmentPositionList().then(res => {
      this.props.dispatch(setWorkflowDepartmentPosition(res.data));
    })
  };

  getNodeList = (formOID) => {
    if (formOID) {
      return newWorkflowService.getNodeList(formOID)
        .then(res => {
          this.setState({
            nodeList: res.data,
          })
        })
    }
  };

  getVersionList = (formOID) => {
    if (formOID) {
      return newWorkflowService.postWorkflowVersionList(formOID, this.props.setOfBooksId)
        .then(res => {
          this.setState({
            data: res.data,
            loading: false,
            copyData: JSON.parse(JSON.stringify(res.data))
          })
        })
        .catch(e => {
          this.setState({
            loading: false,
          });
          errorMessage(e.response);
        })
    }
  };

  handleCopySuccess = () => {
    let { formOID }=this.state;
    this.getVersionList(formOID);
  };

  handleDeleteWorkflow = (record) => {
    Modal.confirm({
      title: messages('setting.key1908')/*注意*/,
      content: messages('setting.key1917')/*确定要删除此审批流吗？*/,
      onOk: () => {
        let { formOID }=this.state;
        this.setState({ loading: true });
        newWorkflowService.deleteWorkflowChain([record.ruleApprovalChainOID]).then(res => {
          this.getVersionList(formOID);
        }).catch(e => {
          this.setState({ loading: false });
          errorMessage(e.response);
        });
      }
    });
  };

  //停用启用审批流
  postChainUsed = (params) => {
    let { formOID }=this.state;
    this.setState({ loading: true });
    newWorkflowService.postChainUsed(params)
      .then(res => {
        this.getVersionList(formOID);
      })
      .catch(e => {
        //复制出的表单有错误数据时提示
        if(e.response && e.response.data.errorCode === '6003'){
          Modal.confirm({
            title: messages('setting.key1908')/*注意*/,
            content:messages('setting.key2010')/*该审批流中存在当前单据无法启用的配置，请先通过编辑改正后再启用*/,
            okText:messages('setting.key2011')/*去编辑*/,
            onOk: () => {
              this.setState({ visible: true, mode: 'edit', version: params.version })
            }
          });
        }else{
          errorMessage(e.response);
        }
        this.setState({ loading: false });
      })
  };

  handleChangeStatus = (record) => {
    // if (!visible) {
    if (!record.used) {
      Modal.confirm({
        title: messages('setting.key1908')/*注意*/,
        content: messages('setting.key1918')/*启用该审批流，会自动停用其他启用中的流程，是否确定？*/,
        onOk: () => {
          this.postChainUsed({ used: true, ruleApprovalChainOID: record.ruleApprovalChainOID, version:record.version})
        }
      });
    } else {
      Modal.confirm({
        title: messages('setting.key1908')/*注意*/,
        content: messages('setting.key1919')/*停用审批流，可能会影响单据提交，确定要停用此审批流吗？*/,
        onOk: () => {
          this.postChainUsed({ used: false, ruleApprovalChainOID: record.ruleApprovalChainOID, version:record.version })
        }
      });
    }

    // }
  };

  onCancel = () => {
    this.props.form.resetFields();
    this.props.close();
  };

  handleClick = (e) => {
    this.setState({
      current: e.key,
    });
  };
  callback = (e) => {
    this.setState({ defaultActiveKey: e })
  };
  onChange = (e) => {
    this.setState({
      checkDisable: !this.state.checkDisable,
    })
  };

  handleSuccess = (formOID) => {
    if (formOID) {
      this.setState({
        visible: false,
      }, () => {
        this.props.onOpen(false);
        this.getVersionList(formOID);
      });
    } else {
      this.props.onOpen(false);
      Modal.confirm({
        title: messages('components.key464')/*提示*/,
        content: messages('setting.key1920')/*尚未保存，是否要退出？*/,
        onOk: () => {
          this.props.onOpen(false);
          //关闭全屏恢复原始数据
          this.setState({
            visible: false,
          });
        }
      });
    }
  };

  handleOpen = (res) => {
    this.props.onOpen(res);
  };

  //显示新版审批流
  handleChangeVisible = (visible) => {
    let { isSave } = this.state;
    if (!visible) {
      if (isSave) {
        this.props.onOpen(false);
        this.setState({
          visible,
        });
      } else {
        this.props.onOpen(true);
        Modal.confirm({
          title: messages('components.key464')/*提示*/,
          content: messages('setting.key1920')/*尚未保存，是否要退出？*/,
          onOk: () => {
            //关闭全屏恢复原始数据
            this.props.onOpen(false);
            this.setState({
              visible,
            });
          }
        });
      }
    } else {
      this.setState({ visible: true, mode: 'create', })
      this.props.onOpen(true);
    }
  };

  handleCancel = () => {
    this.setState({ visible: false })
  }

  render() {
    let { profile }=this.props;
    let { columns, copyData, checkDisable, loading, formOID, defaultActiveKey, visible, mode, version, nodeList, formType } = this.state;
    return (
      <Row className="table-right">
        <Tabs onChange={this.callback} type="card" activeKey={defaultActiveKey}>
          <TabPane tab={messages('setting.key1921')/*流程列表*/} key="1">
            <div className="action-group">
              {profile['branch.workflow.enabled'] &&
              <Button className="add-btn" style={{ marginRight: 10 }}
                      onClick={() => this.handleChangeVisible(true)}
                      type="primary"> {messages('common.create')/*新建*/}
              </Button>}
              <Checkbox
                checked={checkDisable}
                onChange={e => this.onChange(e)}
              > {messages('setting.key1922')/*显示停用流程*/}
              </Checkbox>

            </div>
            <Spin spinning={loading}>
              <div className="workflow-scroll">
                <ResizeTable
                  rowKey="ruleApprovalChainOID"
                  columns={columns}
                  pagination={false}
                  dataSource={checkDisable ? copyData : copyData.filter(item => {return item.used })}
                />
              </div>
            </Spin>
          </TabPane>
          {formType !== '4001' && <TabPane tab={messages('setting.key1412')/*表单配置*/} key="2">
            <div className="right-content">
              {formOID && <FormSetting formOID={formOID}/>}
            </div>
          </TabPane>}
        </Tabs>
        {visible && !loading &&
        <FullScreen animateIn="fadeIn" animateOut="fadeOut" style={{ background: '#E3E5E8' }}>
          <NewWorkflowDetail
            nodeList={nodeList}
            setOfBooksId={this.props.setOfBooksId}
            onSuccess={this.handleSuccess}
            onCancel={this.handleCancel}
            status={mode}
            version={mode == 'edit' && version}
            formOID={formOID}/></FullScreen>}
      </Row>
    )
  }
}

NewWorkingRightContent.PropTypes = {
  onOpenAdditionModal: React.PropTypes.string.func,
  formOID: React.PropTypes.string.isRequired,
  formType: React.PropTypes.string.isRequired,
  onSelectOldDetail: React.PropTypes.string.func,
  onOpen: React.PropTypes.string.func,
  setOfBooksId: React.PropTypes.string
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    company: state.login.company,
    user: state.login.user,
    language: state.main.language
  }
}

const WrappedNewWorkingRightContent = Form.create()(NewWorkingRightContent);

export default connect(mapStateToProps)(WrappedNewWorkingRightContent);
